package com.yixq.soa.service.web.mapper;

import org.apache.ibatis.mapping.MappedStatement;

import tk.mybatis.mapper.entity.EntityColumn;
import tk.mybatis.mapper.entity.EntityTable;
import tk.mybatis.mapper.mapperhelper.EntityHelper;
import tk.mybatis.mapper.mapperhelper.MapperHelper;
import tk.mybatis.mapper.mapperhelper.MapperTemplate;

public class PageProvider extends MapperTemplate {

	public PageProvider(Class<?> mapperClass, MapperHelper mapperHelper) {
		super(mapperClass, mapperHelper);
		// TODO Auto-generated constructor stub
	}
	
	public String selectByPageBounds(MappedStatement ms) {
	    final Class<?> entityClass = getEntityClass(ms);
	    
	    EntityTable table = EntityHelper.getEntityTable(entityClass);
	    StringBuilder sql = new StringBuilder();
	    
	    sql.append("SELECT ");
	    boolean first = true;
	    for (EntityColumn column : table.getEntityClassColumns()) {
	        if(!first) {
	            sql.append(", ");
	        }
	        sql.append(column.getColumn() + " AS " + column.getProperty());
	        first = false;
	    }
	    
	    sql.append(" FROM ");
	    sql.append(table.getName());
	    sql.append(" <where>");
	    first = true;
	    for (EntityColumn column : table.getEntityClassColumns()) {
	    	sql.append("<if test=\""+column.getProperty()+" != null\"> ");
	        if(!first) {
	            sql.append("AND ");
	        }
	        sql.append(column.getColumn() + "=#{" + column.getProperty() + "} ");
	        sql.append("</if>");
	        first = false;
	    }
	    sql.append("</where>");
	    
	    return sql.toString();
	}

}
